<?php

namespace app\service\system\permission;

use core\base\BaseService;
use core\facade\Tree;
use app\model\system\{Menu, User, AuthAccess};
use core\exception\FailedException;
use app\adminapi\validate\system\MenuValidate;
use think\facade\Db;
use think\Paginator;

class MenuService extends BaseService
{

    public function __construct(Menu $model)
    {
        $this->model = $model;
    }


    /**
     * 列表
     *
     * @return Paginator|\think\paginator\driver\Bootstrap
     */
    public function getList()
    {
        $data = $this->model->field('*,id as value')->whereIn("type", [1, 2])->sort('asc')->select()->each(function ($item) {
//            $item->setAttribute("id");
//            $item->setAttr("component");
            $item->set("createBy", 0);
            $item->set("createTime", date("Y-m-d H:i:s", $item->getData("create_time")));
            $item->set("i18nKey", $item->i18n_key);
//            $item->set("icon", $item->icon_type);
            $item->set("iconType", (string)$item->icon_type);
//            $item->setAttr("id");
            $item->set("menuName", $item->title);
            $item->set("menuType", (string)$item->getData("type"));
            $item->set("order", $item->sort);
            $item->set("parentId", $item->pid);
            $item->set("hideInMenu", $item->hidden);

            $item->set("routeName", $item->route_name);
            $item->set("routePath", $item->path);
            $item->set("status", $item->getData("status"));
            $item->set("updateBy", "0");
            $item->set("updateTime", date("Y-m-d H:i:s", $item->getData("update_time")));
            $auths = Db::name("menu")->field("*,id as value,pid as parentId,title as menuName,icon_type as iconType,sort as `order`,hidden as hideInMenu,i18n_key as i18nKey")->where(["pid" => $item->id, "type" => 3])->select()->toArray();
            $item->set("auths", $auths);
            return $item;
        });

        $config = [
            'query' => [], //url额外参数
            'fragment' => '', //url锚点
            'var_page' => 'page', //分页变量
            'list_rows' => 1000, //每页数量
        ];
        return Paginator::make($data->toTree(), 1000, 1, $data->count(), true, $config);
    }


    /**
     * 添加
     * @param array $data
     * @return  int
     */
    public function save($data)
    {
        $this->validate($data);
        $menuid = $this->model->storeBy($data);
        //超级管理员自动写入菜单
        $AuthAccess = app()->make(AuthAccessService::class);
        $AuthAccess->create($menuid, config('system.super_admin_id'));
        return $menuid;
    }


    /**
     * 更新
     * @param string $id
     * @param array $data
     * @return  bool
     */
    public function update($id, $data)
    {
        $this->validate($data);
        $result = $this->model->updateBy($id, $data);
        return $result;
    }


    /**
     * 删除
     * @param string $id
     * @return  bool
     */
    public function delete($id)
    {
        $children = $this->model->where('pid', $id)->find();
        if ($children) {
            throw new FailedException('删除失败,存在子菜单无法删除！');
        }
        try {
            $this->transaction(function () use ($id) {
                //删除菜单数据
                $this->model->deleteBy($id);
                //删除权限关联表数据
                $AuthAccess = app()->make(AuthAccessService::class);
                $AuthAccess->delete($id);
            });
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }


    /**
     * 获取路由
     * @return  array
     */
    public function getRouter()
    {
        $roleid = User::find(request()->uid())->getRolesId();
        $menuid = AuthAccess::getPermission($roleid);
        $routes = $this->model->whereIn('type', [1, 2])->order("sort", 'asc')->select();
        $items = [];
        foreach ($routes as $item) {
            $route = [
                "id" => $item["id"],
                "pid" => $item["pid"],
                "name" => $item["route_name"],
                "path" => $item["path"],
                "item" => $item,
                "component" => $item["component"],
                "meta" => [
                    "title" => $item["title"],
                    "i18nKey" => $item["i18n_key"],
                    "icon" => $item["icon"],
                    "order" => $item["sort"],
                    "roles" => $item["rules"],
                    "hideInMenu" => $item['hidden'],
                    "href" => $item["link_url"],
                ],
            ];
            $items[] = $route;
        }
        $str = <<<html
[
            {
                "name": "exception",
                "path": "/exception",
                "component": "layout.base",
                "meta": {
                    "title": "exception",
                    "i18nKey": "route.exception",
                    "icon": "ant-design:exception-outlined",
                    "order": 7
                },
                "children": [
                    {
                        "name": "exception_403",
                        "path": "/exception/403",
                        "component": "view.403",
                        "meta": {
                            "title": "exception_403",
                            "i18nKey": "route.exception_403",
                            "icon": "ic:baseline-block"
                        }
                    },
                    {
                        "name": "exception_404",
                        "path": "/exception/404",
                        "component": "view.404",
                        "meta": {
                            "title": "exception_404",
                            "i18nKey": "route.exception_404",
                            "icon": "ic:baseline-web-asset-off"
                        }
                    },
                    {
                        "name": "exception_500",
                        "path": "/exception/500",
                        "component": "view.500",
                        "meta": {
                            "title": "exception_500",
                            "i18nKey": "route.exception_500",
                            "icon": "ic:baseline-wifi-off"
                        }
                    }
                ]
            },
            {
                "name": "about",
                "path": "/about",
                "component": "layout.base\$view.about",
                "meta": {
                    "title": "about",
                    "i18nKey": "route.about",
                    "icon": "fluent:book-information-24-regular",
                    "order": 10
                }
            },
            {
                "name": "function",
                "path": "/function",
                "component": "layout.base",
                "meta": {
                    "title": "function",
                    "i18nKey": "route.function",
                    "icon": "icon-park-outline:all-application",
                    "order": 6
                },
                "children": [
                    {
                        "name": "function_hide-child",
                        "path": "/function/hide-child",
                        "meta": {
                            "title": "function_hide-child",
                            "i18nKey": "route.function_hide-child",
                            "icon": "material-symbols:filter-list-off",
                            "order": 2
                        },
                        "redirect": "/function/hide-child/one",
                        "children": [
                            {
                                "name": "function_hide-child_one",
                                "path": "/function/hide-child/one",
                                "component": "view.function_hide-child_one",
                                "meta": {
                                    "title": "function_hide-child_one",
                                    "i18nKey": "route.function_hide-child_one",
                                    "icon": "material-symbols:filter-list-off",
                                    "hideInMenu": true,
                                    "activeMenu": "function_hide-child"
                                }
                            },
                            {
                                "name": "function_hide-child_three",
                                "path": "/function/hide-child/three",
                                "component": "view.function_hide-child_three",
                                "meta": {
                                    "title": "function_hide-child_three",
                                    "i18nKey": "route.function_hide-child_three",
                                    "hideInMenu": true,
                                    "activeMenu": "function_hide-child"
                                }
                            },
                            {
                                "name": "function_hide-child_two",
                                "path": "/function/hide-child/two",
                                "component": "view.function_hide-child_two",
                                "meta": {
                                    "title": "function_hide-child_two",
                                    "i18nKey": "route.function_hide-child_two",
                                    "hideInMenu": true,
                                    "activeMenu": "function_hide-child"
                                }
                            }
                        ]
                    },
                    {
                        "name": "function_multi-tab",
                        "path": "/function/multi-tab",
                        "component": "view.function_multi-tab",
                        "meta": {
                            "title": "function_multi-tab",
                            "i18nKey": "route.function_multi-tab",
                            "icon": "ic:round-tab",
                            "multiTab": true,
                            "hideInMenu": true,
                            "activeMenu": "function_tab"
                        }
                    },
                    {
                        "name": "function_request",
                        "path": "/function/request",
                        "component": "view.function_request",
                        "meta": {
                            "title": "function_request",
                            "i18nKey": "route.function_request",
                            "icon": "carbon:network-overlay",
                            "order": 3
                        }
                    },
                    {
                        "name": "function_super-page",
                        "path": "/function/super-page",
                        "component": "view.function_super-page",
                        "meta": {
                            "title": "function_super-page",
                            "i18nKey": "route.function_super-page",
                            "icon": "ic:round-supervisor-account",
                            "order": 5
                        }
                    },
                    {
                        "name": "function_tab",
                        "path": "/function/tab",
                        "component": "view.function_tab",
                        "meta": {
                            "title": "function_tab",
                            "i18nKey": "route.function_tab",
                            "icon": "ic:round-tab",
                            "order": 1
                        }
                    },
                    {
                        "name": "function_toggle-auth",
                        "path": "/function/toggle-auth",
                        "component": "view.function_toggle-auth",
                        "meta": {
                            "title": "function_toggle-auth",
                            "i18nKey": "route.function_toggle-auth",
                            "icon": "ic:round-construction",
                            "order": 4
                        }
                    }
                ]
            },
            {
                "name": "home",
                "path": "/home",
                "component": "layout.base\$view.home",
                "meta": {
                    "title": "home",
                    "i18nKey": "route.home",
                    "icon": "mdi:monitor-dashboard",
                    "order": 1
                }
            },
            {
                "name": "manage",
                "path": "/manage",
                "component": "layout.base",
                "meta": {
                    "title": "manage",
                    "i18nKey": "route.manage",
                    "icon": "carbon:cloud-service-management",
                    "order": 9
                },
                "children": [
                    {
                        "name": "manage_menu",
                        "path": "/manage/menu",
                        "component": "view.manage_menu",
                        "meta": {
                            "title": "manage_menu",
                            "i18nKey": "route.manage_menu",
                            "icon": "material-symbols:route",
                            "order": 3,
                            "keepAlive": true
                        }
                    },
                    {
                        "name": "manage_role",
                        "path": "/manage/role",
                        "component": "view.manage_role",
                        "meta": {
                            "title": "manage_role",
                            "i18nKey": "route.manage_role",
                            "icon": "carbon:user-role",
                            "order": 2
                        }
                    },
                    {
                        "name": "manage_user",
                        "path": "/manage/user",
                        "component": "view.manage_user",
                        "meta": {
                            "title": "manage_user",
                            "i18nKey": "route.manage_user",
                            "icon": "ic:round-manage-accounts",
                            "order": 1
                        }
                    },
                    {
                        "name": "manage_user-detail",
                        "path": "/manage/user-detail/:id",
                        "component": "view.manage_user-detail",
                        "props": true,
                        "meta": {
                            "title": "manage_user-detail",
                            "i18nKey": "route.manage_user-detail",
                            "hideInMenu": true,
                            "activeMenu": "manage_user"
                        }
                    }
                ]
            },
            {
                "name": "multi-menu",
                "path": "/multi-menu",
                "component": "layout.base",
                "meta": {
                    "title": "multi-menu",
                    "i18nKey": "route.multi-menu",
                    "order": 8
                },
                "children": [
                    {
                        "name": "multi-menu_first",
                        "path": "/multi-menu/first",
                        "meta": {
                            "title": "multi-menu_first",
                            "i18nKey": "route.multi-menu_first",
                            "order": 1
                        },
                        "children": [
                            {
                                "name": "multi-menu_first_child",
                                "path": "/multi-menu/first/child",
                                "component": "view.multi-menu_first_child",
                                "meta": {
                                    "title": "multi-menu_first_child",
                                    "i18nKey": "route.multi-menu_first_child"
                                }
                            }
                        ]
                    },
                    {
                        "name": "multi-menu_second",
                        "path": "/multi-menu/second",
                        "meta": {
                            "title": "multi-menu_second",
                            "i18nKey": "route.multi-menu_second",
                            "order": 2
                        },
                        "children": [
                            {
                                "name": "multi-menu_second_child",
                                "path": "/multi-menu/second/child",
                                "meta": {
                                    "title": "multi-menu_second_child",
                                    "i18nKey": "route.multi-menu_second_child"
                                },
                                "children": [
                                    {
                                        "name": "multi-menu_second_child_home",
                                        "path": "/multi-menu/second/child/home",
                                        "component": "view.multi-menu_second_child_home",
                                        "meta": {
                                            "title": "multi-menu_second_child_home",
                                            "i18nKey": "route.multi-menu_second_child_home"
                                        }
                                    }
                                ]
                            }
                        ]
                    }
                ]
            },
            {
                "name": "user-center",
                "path": "/user-center",
                "component": "layout.base\$view.user-center",
                "meta": {
                    "title": "user-center",
                    "i18nKey": "route.user-center",
                    "hideInMenu": true
                }
            }
        ] 
html;
//return json_decode($str, true);

        return Tree::init($items, ['pk' => "id", 'parentKey' => "pid"])->buildTree(0);
    }


    /**
     * 获取全部菜单节点数据
     * @return  array
     */
    public static function getRuleAll()
    {
        $map[] = ['type', '<>', 3];
        $node = Menu::field('id,title,pid')->where($map)->order('sort', 'asc')->select()->toTree();
        return $node;
    }


    /**
     * 验证
     * @throws \think\ValidateException
     */
    public function validate($data)
    {
        if (!isset($data['type'])) {
            throw new FailedException('菜单类型不能为空');
        }
        if ($data['type'] == 2) {
            //验证权限节点
            validate(MenuValidate::class)->scene('rules')->check($data);
        } else {
            if (!isset($data['open_type'])) {
                throw new FailedException('打开方式不能为空');
            }
            if ($data['open_type'] == 1) {
                validate(MenuValidate::class)->scene('linkUrl')->check($data);
            } else if ($data['open_type'] == 2) {
                validate(MenuValidate::class)->scene('externalLink')->check($data);
            } else {
                validate(MenuValidate::class)->check($data);
            }
        }
    }

    private function data_to_tree(array $items)
    {

    }
}
